package it.polimi.swimv2.session;

import it.polimi.swimv2.entities.Ability;
import it.polimi.swimv2.entities.User;
import it.polimi.swimv2.exception.ModifyException;
import it.polimi.swimv2.exception.UserDataError;
import it.polimi.swimv2.exception.UserDataException;
import it.polimi.swimv2.remote.UserManagerRemote;
import it.polimi.swimv2.util.UserDataValidator;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class UserManager
 */
@Stateless
public class UserManager implements UserManagerRemote {

	@PersistenceContext(unitName = "swimv2")
	private EntityManager em;

	/**
	 * Default constructor.
	 */
	public UserManager() {

	}

	@Override
	public boolean modifyPassword(String username, String oldPwd, String newPwd)
			throws ModifyException, UserDataException {

		checkPwd(newPwd);
		User u = em.find(User.class, username);
		if (u != null && u.checkPassword(oldPwd) == true) {		
			u.setPassword(newPwd);
			em.merge(u);
			em.flush();
		} else {
			throw new ModifyException();
		}
		return true;
	}

	

	@Override
	public boolean modifyData(String username, String email, String city,
			String phone) throws UserDataException, ModifyException {
		checkData(email, city, phone);
		User u = em.find(User.class, username);
		if (u != null) {
			u.setEmail(email);
			u.setCity(city);
			u.setPhone(phone);
			em.merge(u);
			em.flush();
			return true;
		}else{
			throw new ModifyException();
		}
	}

	private void checkData(String email, String city, String phone)
			throws UserDataException {
		
		if(!UserDataValidator.emailIsValid(email)){
			throw new UserDataException(UserDataError.EMAILERR);
		}
		if(!UserDataValidator.cityIsValid(city)){
			throw new UserDataException(UserDataError.CITYERR);
		}
		if(!UserDataValidator.phoneIsValid(phone)){
			throw new UserDataException(UserDataError.PHONEERR);
		}
	
	}
	
	private boolean checkPwd(String pwd) throws UserDataException {
		if (UserDataValidator.passwordIsValid(pwd)==false) {
			throw new UserDataException(UserDataError.PWDERR);
		}
		return true;
	}

	@Override
	public boolean addAbility(String username, String abilityName)
			throws ModifyException {
		Ability a = em.find(Ability.class, abilityName);
		User u = em.find(User.class, username);
		if (a == null || u == null) {
			throw new ModifyException();
		}
		if(!u.getDeclaredAbilities().contains(a)){
			u.addAbility(a);
			em.flush();
			return true;
		}
		return false;
	}

	@Override
	public boolean removeAbility(String username, String abilityName)
			throws ModifyException {
		Ability a = em.find(Ability.class, abilityName);
		User u = em.find(User.class, username);
		if (a == null || u == null) {
			throw new ModifyException();
		}
		u.removeAbility(a);
		em.flush();
		return true;
	}

}
